import Taro from '@tarojs/taro'
import { Block, Navigator, View, Button, Text, Image } from '@tarojs/components'
import { useEffect, useState, useRef, useReducer, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import Header from '../../../components/public/header/Header';
import { CardHeader } from './tpl/CardHeader'
import { ContactInfo } from './tpl/ContactInfo'
import apiUrl from '../../../utils/urls'
import mayKey from '../../../utils/storageKeyMap'
import { feedsReport } from '../../../utils/feedsReport'
import './card.less'
import { getCardMainDetail } from '../../../service/data';
import { CARDDETAIL } from '../../../constants/card';
import { CardGif } from './tpl/CardGif';



export default function Card() {
  const dispatch = useDispatch();
  const __companyInfo = useSelector(state => state.company.__companyInfo);
  const __companyBase = useSelector(state => state.company.__companyBase);
  const __cardDetail = useSelector(state => state.card.__cardDetail);
  const cardId = useSelector(state => state.card.__cardId);
  // 设置标题
  const [title, setTitle] = useState('')
  const [progressNum, setProgressNum] = useState(0)
  useEffect(() => {
    const t = __cardDetail && __cardDetail.cardName
    setTitle(t)
  }, [__cardDetail])

  const [cardMainDetail, setCardMainDetail] = useState('')

  const getCardData = useCallback(function getCardData(r) {
    console.log('__companyBase', r);
    const { companyLogo, shortName, companyName } = __companyBase
    r.company = {
      logo: companyLogo || apiUrl.defaultLogoUrl,
      shortName: shortName,
      companyName: companyName,
      displayCompanyName: shortName || companyName
    }
    r.cardId = cardId
    r.cardPositionTemp = r.cardPosition.split(/\s{1,}/g)
    if (r.labels && r.labels.length > 0) {
      r.labels.sort((i, j) => j.thumbUpCount - i.thumbUpCount)
    }
    updateCardOptions(r)
    setCardMainDetail(r)
    dispatch({ type: CARDDETAIL, payload: r })
    Taro.setStorageSync(mayKey.CARD_DETAIL_KEY, r)
  }, [__companyBase, cardId, dispatch])

  useEffect(() => {
    const r = async () => {
      if (!cardId) return
      const res = await getCardMainDetail({ cardId })
      getCardData(res)
    }
   
    r()
  }, [cardId, getCardData])

  useEffect(() => {
    const delay = 200
    const update = () => {
      clearTimeout(progressTimer)
      if (cardMainDetail || progressNum >= 90) return

      setProgressNum(progressNum + Math.round(Math.random() * 10))

      progressTimer = setTimeout(update, delay)
    }

    let progressTimer = setTimeout(update, delay)
    return () => clearTimeout(progressTimer)
  }, [cardMainDetail, progressNum])

  function updateCardOptions(r) {
    const {
      mobile,
      telephone,
      wechat,
      cardEmail,
      address,
      longitude,
      latitude,
      wechatCodeUrl
    } = r
    const options = (r.options = [])

    if (mobile) {
      options.push({
        value: mobile,
        title: '拨打',
        type: 'mobile',
        action: 'call',
        icon: 'icon-icon_Phone'
      })
    }

    if (!mobile && telephone) {
      options.push({
        value: telephone,
        title: '拨打',
        type: 'telephone',
        action: 'call',
        icon: 'icon-icon_Phone'
      })
    }

    if (wechat) {
      options.push({
        value: wechat,
        title: wechatCodeUrl ? '添加微信' : '复制微信ID号',
        type: 'wechat',
        action: 'copy',
        icon: 'icon-weixin'
      })
    }
    if (cardEmail) {
      options.push({
        value: cardEmail,
        title: '复制邮箱',
        type: 'cardEmail',
        action: 'copy',
        icon: 'icon-youxiang'
      })
    }
    if (address) {
      options.push({
        value: address,
        title: longitude && latitude ? '现在出发' : '复制地址',
        type: 'address',
        action: longitude && latitude ? 'openmap' : 'copy',
        icon: 'icon-icon_navigation'
      })
    }

    if (mobile && telephone) {
      options.push({
        value: telephone,
        title: '拨打',
        type: 'telephone',
        action: 'call',
        icon: 'icon-icon_Phone'
      })
    }
  }
  function goSweepCode() {
    Taro.navigateTo({
      url: `/subs/card/pages/sweep-code/sweep-code?cardId=${cardId}`
    })
    feedsReport('SEND_CARD_CODE')
  }


  // 点击标题
  function handleTapTitle() {
    console.log('点击标题事件');
  }
  return (
    <Block>
      <Header title={title || __companyInfo.navigateConfigVO.navFooterNames[0]} showUserAvatar={false} showTitleIcon handleTapTitle={handleTapTitle} />
      {cardMainDetail && <Block>

        {/* 名片模版 */}
        <CardHeader card={cardMainDetail} />
        {/* 名片码icon */}
        <View className='card_detail_banner_box'>
          <View className='sweep-code' onClick={goSweepCode}>
            <Image src='http://resource.aijiatui.com/ai-img/mini-program/mini-all/qr3.png' />
          </View>
        </View>
        {/* 联系信息 */}
        <ContactInfo card={cardMainDetail} />

        {/* 添加 社康通运维位置 */}
        <Navigator style={{ margin: '16px' }} hover-class='none' url='/subs/ftskt/pages/index/index'>
          <Image style={{ width: '343px', height: '70px' }} mode='aspectFit' src='https://poc-cdn.aijiatui.com/entrepreneur-club/mini-prog-resources/futian/ftskt.png'></Image>
        </Navigator>
        {/*  个人简介  */}
        {/*  评价  */}
        {/*  推荐活动  */}
        {/*  推荐微事我言  */}
        {/*  推荐有奖问答  */}
        {/*  同乡/校友确认窗  */}
        {/*  名片评论  */}
        {/*  我的同事  */}
        {/* 视频  */}
        {/*  动态模块  */}
        {/*  动态分享模块  */}
        {/*  删除评论 action-sheet  */}
        {/* 相册 */}
        {/*  分享组件  */}
        {/*  拨打电话  */}
        {/*  IM浮窗  */}
        {/*  名片等待添加gif  */}

      </Block>}

      {!cardMainDetail && <CardGif progressNum={progressNum} />}
    </Block>

  )
}



